/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * CadastroPessoa.java
 *
 * Created on 23/06/2011, 18:11:47
 */
package GUI.pessoa;

import bd.MySql;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.util.ArrayList;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JOptionPane;

/**
 *
 * @author Marcio
 */
public class CadastroPessoa extends javax.swing.JFrame {

    private boolean editar = false;

    /** Creates new form CadastroPessoa */
    public CadastroPessoa() {
        this(false);
    }

    public CadastroPessoa(boolean editar) {
        this.editar = editar;
        initComponents();
        this.jComboBox1.addItemListener(new OuvinteComboBox());
        this.setLocationRelativeTo(null);
    }

    public CadastroPessoa(String id) {
        this(true);

        if (this.editar) {
            jTextField2.setEditable(false);
            jComboBox1.setEnabled(false);
            MySql conn = new MySql(GUI.Main.config);

            String query = "SELECT * FROM pessoa WHERE cpf=" + id;

            ArrayList<ArrayList<String>> resultado = conn.getTable(query);

            jTextField1.setText(resultado.get(0).get(1));
            jTextField2.setText(id);
            jTextField3.setText(resultado.get(0).get(2));
            jTextField4.setText(resultado.get(0).get(7));
            jTextField5.setText(resultado.get(0).get(8));

            if (resultado.get(0).get(3).equals("1")) {
                jComboBox1.setSelectedIndex(2);
                query = "SELECT * FROM diretor WHERE cpf=" + id;
                jLabel7.setText("Cargo");
            } else if (resultado.get(0).get(4).equals("1")) {
                jComboBox1.setSelectedIndex(0);
                query = "SELECT * FROM integrante WHERE cpf=" + id;
                jLabel7.setText("Idade");
            } else if (resultado.get(0).get(5).equals("1")) {
                jComboBox1.setSelectedIndex(1);
                query = "SELECT * FROM jurado WHERE cpf=" + id;
                jLabel7.setText("Atividade");
            } else {
                jComboBox1.setSelectedIndex(3);
                query = "SELECT * FROM espectador WHERE cpf=" + id;
                jLabel7.setText("Idade");
            }
            jTextField6.setText(conn.getTable(query).get(0).get(1));
        }
    }

    private class ComboModel extends DefaultComboBoxModel {

        public ComboModel() {
            this.addElement("Integrante");
            this.addElement("Jurado");
            this.addElement("Diretor");
            this.addElement("Espectador");
        }
    }

    private class OuvinteComboBox implements ItemListener {

        public void itemStateChanged(ItemEvent e) {
            if (e.getItem().toString().equals("Integrante")) {
                jLabel7.setText("Idade");
            } else if (e.getItem().toString().equals("Jurado")) {
                jLabel7.setText("Atividade");
            } else if (e.getItem().toString().equals("Diretor")) {
                jLabel7.setText("Cargo");
            } else if (e.getItem().toString().equals("Espectador")) {
                jLabel7.setText("Idade");
            }
        }
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        jLabel5 = new javax.swing.JLabel();
        jTextField1 = new javax.swing.JTextField();
        jTextField2 = new javax.swing.JTextField();
        jTextField3 = new javax.swing.JTextField();
        jTextField4 = new javax.swing.JTextField();
        jTextField5 = new javax.swing.JTextField();
        jComboBox1 = new javax.swing.JComboBox();
        jLabel6 = new javax.swing.JLabel();
        jPanel2 = new javax.swing.JPanel();
        jLabel7 = new javax.swing.JLabel();
        jTextField6 = new javax.swing.JTextField();
        jButton1 = new javax.swing.JButton();
        jButton2 = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Cadastrar Pessoa");
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowClosed(java.awt.event.WindowEvent evt) {
                formWindowClosed(evt);
            }
            public void windowClosing(java.awt.event.WindowEvent evt) {
                formWindowClosing(evt);
            }
        });

        jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder("Dados"));

        jLabel1.setText("Nome");

        jLabel2.setText("CPF");

        jLabel3.setText("Endereço");

        jLabel4.setText("Telefone");

        jLabel5.setText("Celular");

        jTextField2.setColumns(16);

        jTextField4.setColumns(16);

        jTextField5.setColumns(16);

        jComboBox1.setModel(new ComboModel());

        jLabel6.setText("Tipo");

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel1)
                    .addComponent(jLabel2)
                    .addComponent(jLabel3)
                    .addComponent(jLabel4)
                    .addComponent(jLabel5)
                    .addComponent(jLabel6))
                .addGap(10, 10, 10)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jComboBox1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jTextField2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jTextField4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jTextField5, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jTextField3, javax.swing.GroupLayout.DEFAULT_SIZE, 293, Short.MAX_VALUE)
                    .addComponent(jTextField1, javax.swing.GroupLayout.DEFAULT_SIZE, 293, Short.MAX_VALUE))
                .addContainerGap())
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(jTextField2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel3)
                    .addComponent(jTextField3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jTextField4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel4))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jTextField5, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel5))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jComboBox1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel6))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        jPanel2.setBorder(javax.swing.BorderFactory.createTitledBorder("Dados Adicionais"));

        jLabel7.setText("Idade");

        jTextField6.setColumns(16);

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel7, javax.swing.GroupLayout.PREFERRED_SIZE, 53, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jTextField6, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(167, Short.MAX_VALUE))
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel7)
                    .addComponent(jTextField6, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        jButton1.setText("Cancelar");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        jButton2.setText("Ok");
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addComponent(jButton2)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jButton1)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jButton1)
                    .addComponent(jButton2))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
        // Pega os dados inseridos pelo usuário
        String nome = jTextField1.getText();
        String cpf = jTextField2.getText();
        String endereco = jTextField3.getText();
        String telefone = jTextField4.getText();
        String celular = jTextField5.getText();
        String adicional = jTextField6.getText();

        // adiciona aspas nas strings para evitar erro no SQL
        if (endereco.equals("")) {
            endereco = null;
        } else {
            endereco = "\"" + endereco + "\"";
        }

        if (telefone.equals("")) {
            telefone = null;
        } else {
            telefone = "\"" + telefone + "\"";
        }

        if (celular.equals("")) {
            celular = null;
        } else {
            celular = "\"" + celular + "\"";
        }

        if (adicional.equals("")) {
            adicional = null;
        } else {
            adicional = "\"" + adicional + "\"";
        }

        // identifica o tipo da pessoa que está sendo cadastrada
        boolean jurado = false;
        boolean integrante = false;
        boolean diretor = false;
        boolean espectador = false;

        if (jComboBox1.getSelectedIndex() == 0) {
            integrante = true;
        } else if (jComboBox1.getSelectedIndex() == 1) {
            jurado = true;
        } else if (jComboBox1.getSelectedIndex() == 2) {
            diretor = true;
        } else if (jComboBox1.getSelectedIndex() == 3) {
            espectador = true;
        }

        if (nome.equals("") || cpf.equals("")) { // exibe mensagem de erro caso o campo de nome ou de cpf ou os dois não estejam preenchidos
            JOptionPane.showMessageDialog(this, "Nome e CPF são campos obrigatórios!", "Erro", JOptionPane.ERROR_MESSAGE);
        } else { // caso contrário, insere os dados no banco de dados
            if (!this.editar) {
                String query = "INSERT INTO pessoa (nome,cpf,endereco,telefone1,telefone2,diretor,integrante,jurado,espectador) VALUES (\"" + nome + "\"," + cpf + "," + endereco + "," + telefone + "," + celular + "," + diretor + "," + integrante + "," + jurado + "," + espectador + ")";
                //System.out.println(query);
                MySql conn = new MySql(GUI.Main.config);
                conn.insert(query);
                if (integrante) {
                    query = "INSERT INTO integrante(cpf,idadeInte) VALUES (" + cpf + "," + adicional + ")";
                } else if (jurado) {
                    query = "INSERT INTO jurado (cpf,atividade) VALUES (" + cpf + "," + adicional + ")";
                } else if (diretor) {
                    query = "INSERT INTO diretor (cpf,cargo) VALUES (" + cpf + "," + adicional + ")";
                } else if (espectador) {
                    query = "INSERT INTO espectador (cpf,idadeEspec) VALUES (" + cpf + "," + adicional + ")";
                }

                conn.insert(query);
                this.setVisible(false);
                this.dispose();
                //System.out.println(query);
            } else {
                String query = "UPDATE pessoa " +
                        "SET nome=\"" + nome +
                        "\",endereco=" + endereco +
                        ",telefone1=" + telefone +
                        ",telefone2=" + celular +
                        ",diretor=" + diretor +
                        ",integrante=" + integrante +
                        ",jurado=" + jurado +
                        ",espectador=" + espectador +
                        " WHERE cpf=" + cpf;
                System.out.println(query);
                MySql conn = new MySql(GUI.Main.config);
                conn.insert(query);
            }
        }
    }//GEN-LAST:event_jButton2ActionPerformed

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        // TODO add your handling code here:
        this.setVisible(false);
        this.dispose();
    }//GEN-LAST:event_jButton1ActionPerformed

    private void formWindowClosing(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowClosing
        // TODO add your handling code here:
        this.setVisible(false);
    }//GEN-LAST:event_formWindowClosing

    private void formWindowClosed(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowClosed
        // TODO add your handling code here:
        this.dispose();
    }//GEN-LAST:event_formWindowClosed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                new CadastroPessoa().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JComboBox jComboBox1;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JTextField jTextField1;
    private javax.swing.JTextField jTextField2;
    private javax.swing.JTextField jTextField3;
    private javax.swing.JTextField jTextField4;
    private javax.swing.JTextField jTextField5;
    private javax.swing.JTextField jTextField6;
    // End of variables declaration//GEN-END:variables
}
